import React, {
  PureComponent, useContext, useEffect, useRef, useState,
 } from 'react'
 import {
    Modal, Pagination, Button, message, Select, Spin, Empty, Row, Col, Input,
 } from 'antd'
 import { connect, history } from '@umijs/max'
 import { HufuCard, InputSearch } from '@/components'
 import DataSource from './dataSource'
 import styles from './index.less'
 import Tools from '@/utils/Tools'
 import { deleteProject } from './api'

 const { Option } = Select
 const Bus = Tools.Bus

@connect(({ global }) => ({ ...global }))
export default class WorkSpace extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      data: [],
      spinning: false,
      dsTypes: [{
        name: 'Hive',
        id: 'Hive',
      }, {
        name: 'PostgreSQL',
        id: 'PostgreSQL',
      }, {
        name: 'Sap Hana',
        id: 'Sap',
      }, {
        name: 'TiDB',
        id: 'TiDB',
      }, {
        name: 'MatrixDB',
        id: 'MatrixDB',
      }, {
        name: '人大金仓',
        id: 'KINGBASE8',
      }, {
        name: '达梦',
        id: 'DM',
      },
      ],
    }
    this.addDataSourceRef = React.createRef()
  }

  componentDidMount() {
    Bus.emit('UpdateAuth')
  }

  getProjectLists = () => {
    Bus.emit('UpdateAuth')
  }

  newWorkspace = () => {
    this.addDataSourceRef.current.openModal()
  }

  render() {
    const {
      data, orderBy, spinning, dsTypes,
    } = this.state
    const { projectLists, isLoginLoading } = this.props
    return (
      <div className={styles.pro_list_box}>
        <div className={styles.pro_list_lit}>
          <span className={styles.pro_list_header_title}>
            项目列表
            <InputSearch
              placeholder="项目名称"
              value={this.state.projectName}
              onChange={(e) => {
                this.setState({
                  projectName: e.target.value,
                })
              }}
              // onSearch={this.projectGetProjects.bind(this)}
              style={{ marginLeft: '.24rem', marginBotton: '0rem', width: '1.6rem' }}
            />
          </span>
          <Button
            style={{ width: '.9rem', float: 'right' }}
            type="primary"
            onClick={this.newWorkspace}
          >
            新建项目
          </Button>
        </div>
        <Spin spinning={isLoginLoading}>
          <div className={styles.pro_list}>
            {projectLists && projectLists.length ? (
              <Row gutter={[24, 24]}>
                {
                  projectLists.map((item, key) => (
                    <Col key={key} className="gutter-row" span={8}>
                      <HufuCard
                        title={item.projectName}
                        desc={
                          item.description
                            ? item.description
                            : '暂无相关描述信息...'
                        }
                        deleteClick={async () => {
                          let deletValue = ''
                          const confirmed = await Modal.confirm({
                            title: '确认要删除这个工作空间吗？',
                            content: (
                              <>
                                <span>{`空间删除后，数据将无法恢复，请输入 ${item.projectName} 空间名称进行删除。`}</span>
                                <br />
                                <Input
                                  placeholder="请输入空间名称"
                                  onChange={(e) => { deletValue = e.target.value }}
                                  style={{ marginTop: '0.12rem' }}
                                />
                              </>
                            ),
                            onOk(close) {
                              if (deletValue === item.projectName) {
                                deleteProject({ projectId: item.id }).then((res) => {
                                  message.success('删除成功！')
                                  sessionStorage.removeItem('defaultWorkSpace')
                                  sessionStorage.removeItem('projectId')
                                  Bus.emit('UpdateAuth')
                                  close()
                                })
                              } else {
                                message.error('输入的空间名称与项目名称不匹配，请重新输入！')
                              }
                            },
                          })
                        }}
                        enterClick={() => {
                          Bus.emit('projectClick', item)
                        }}
                        titleClick={() => {
                          Bus.emit('projectClick', item)
                        }}
                        apiNum={item.apiNum}
                        indexNum={item.indexNum}
                        integrateTaskNum={item.integrateTaskNum}
                        registerDsNum={item.registerDsNum}
                        tableNum={item.tableNum}
                        userNum={item.userNum}
                        createTime={item.createTime}
                        developTaskNum={item.developTaskNum}
                      />
                    </Col>
                    ))
                  }
              </Row>
              ) : (
                <Empty
                  description={<span>暂无项目</span>}
                  image={<span className={styles.empty_img} />}
                />
              )}
          </div>
        </Spin>
        {data && data.length ? (
          <div className="table-list-pages">
            <div className="pages">
              <Pagination
                // showQuickJumper
                current={this.state.pageNum}
                total={(this.state.total / this.state.pageSize) * 10}
                size={this.state.pageSize}
                onChange={(pageNum) => {
                  this.setState(
                    {
                      pageNum,
                    },
                    this.projectGetProjects,
                  )
                }}
              />
            </div>
            <div className="pages-l">
              共{' '}
              <span style={{ fontWeight: 600 }} className="color-main">
                {this.state.total}
              </span>{' '}
              个
            </div>
          </div>
        ) : null}
        <DataSource
          id={null}
          title="新建工作空间"
          dsTypes={dsTypes}
          clearTable={this.getProjectLists}
          clearIndex={() => {}}
          ref={this.addDataSourceRef}
          isEdit={false}
          isCheck={false}
          index={0}
        />
      </div>
    )
  }
}
